package com.lsyw.intergrate.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsyw.intergrate.common.Result;
import com.lsyw.intergrate.entity.MSamplingPlan;
import com.lsyw.intergrate.entity.Massif;
import com.lsyw.intergrate.entity.MassifGrid;
import com.lsyw.intergrate.entity.MassifUser;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.lsyw.intergrate.service.MSamplingPlanService;
import com.lsyw.intergrate.service.MassifGridService;
import com.lsyw.intergrate.service.MassifService;
import com.lsyw.intergrate.service.MassifUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 手工采样计划 前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2024-01-18
 */
@Api(tags = "手工采样计划")
@RestController
@RequestMapping("/m-sampling-plan")
public class MSamplingPlanController {

    @Autowired
    private MassifService massifService;
    @Autowired
    private MSamplingPlanService mSamplingPlanService;
    @Autowired
    private MassifUserService massifUserService;
    @Autowired
    private MassifGridService massifGridService;

    /**
     * 通过id查询
     */
    @GetMapping("/get-by-id")
    @ApiOperation(value = "通过id查询", notes = "通过id查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    public Result getById(String id) {
        return Result.successResult(mSamplingPlanService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增", notes = "新增", httpMethod = "POST")
    public Result save(@RequestBody MSamplingPlan mSamplingPlan) {
        mSamplingPlanService.save(mSamplingPlan);
        return Result.successResult(null);
    }

    /**
     * 通过id删除
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    @GetMapping("/delete")
    public Result delete(String id) {
        MSamplingPlan byId = mSamplingPlanService.getById(Long.parseLong(id));
        byId.setDelFlag(1);
        this.mSamplingPlanService.updateById(byId);
        return Result.successResult(null);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改", notes = "修改", httpMethod = "POST")
    public Result updateById(@RequestBody MSamplingPlan mSamplingPlan) {
        mSamplingPlanService.updateById(mSamplingPlan);
        return Result.successResult(null);
    }


    /**
     * 查询列表
     */
    @PostMapping("/list")
    public Result list(@RequestBody MSamplingPlanReqVo mSamplingPlan) {
        final LambdaQueryWrapper<MSamplingPlan> lambda = new QueryWrapper<MSamplingPlan>().lambda();
        this.buildCondition(lambda, mSamplingPlan);
        lambda.eq(MSamplingPlan::getDelFlag,0);
        return Result.successResult(mSamplingPlanService.list(lambda));
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "POST")
    public Result page(@RequestBody PageInfo pageInfo) {
        Page<MSamplingPlan> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        final LambdaQueryWrapper<MSamplingPlan> lambda = new QueryWrapper<MSamplingPlan>().lambda();
        Map<String, Object> condition = pageInfo.getCondition();
        if (condition.get("name") != null && !StringUtils.isEmpty(condition.get("name").toString())) {
            lambda.like(MSamplingPlan::getName, condition.get("name"));
        }
        if (condition.get("massifId") != null && !StringUtils.isEmpty(condition.get("massifId").toString())) {
            lambda.like(MSamplingPlan::getMassifId, condition.get("massifId"));
        }
        if (condition.get("type") != null && !StringUtils.isEmpty(condition.get("type").toString())) {
            lambda.like(MSamplingPlan::getType, condition.get("type"));
        }
        lambda.like(MSamplingPlan::getDelFlag, 0);
        Page<MSamplingPlan> planPage = this.mSamplingPlanService.page(page, lambda);
        List<MSamplingPlan> records = planPage.getRecords();


        for (int i = 0; i < records.size(); i++) {
            List<String> userName = new ArrayList<>();
            List<String> wgName = new ArrayList<>();
            String massifId = records.get(i).getMassifId();
            Massif massif = this.massifService.getById(massifId);
            if (massif!=null ){
                records.get(i).setMassifName(massif.getName());
            }
            String head = records.get(i).getHead();
            String[] split = head.split(",");
            for (String id :split){
                MassifUser massifUser = this.massifUserService.getById(id);
                if (massifUser!=null){
                    userName.add(massifUser.getName());
                }
            }
            String lettersCommaSeparated = String.join(",", userName);
            records.get(i).setMassifUserName(lettersCommaSeparated);

            String massifGridIds = records.get(i).getMassifGridIds();
            String[] massifGridIdss = massifGridIds.split(",");
            for (String id :massifGridIdss){
                MassifGrid massifGrid = this.massifGridService.getById(id);
                if (massifGrid!=null){
                    wgName.add(massifGrid.getName());
                }
            }
            String wgCommaSeparated = String.join(",", wgName);
            records.get(i).setMassifGridNames(wgCommaSeparated);
        }
        planPage.setRecords(records);
        return Result.successResult(planPage);
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<MSamplingPlan> lambda, MSamplingPlanReqVo param) {
        if (!StringUtils.isEmpty(param.getId())) {
            lambda.eq(MSamplingPlan::getId, param.getId());
        }
        if (!StringUtils.isEmpty(param.getName())) {
            lambda.eq(MSamplingPlan::getName, param.getName());
        }
        if (!StringUtils.isEmpty(param.getMassifGridIds())) {
            lambda.eq(MSamplingPlan::getMassifGridIds, param.getMassifGridIds());
        }
        if (!StringUtils.isEmpty(param.getHead())) {
            lambda.eq(MSamplingPlan::getHead, param.getHead());
        }
        if (!StringUtils.isEmpty(param.getMethod())) {
            lambda.eq(MSamplingPlan::getMethod, param.getMethod());
        }
        if (!StringUtils.isEmpty(param.getContent())) {
            lambda.eq(MSamplingPlan::getContent, param.getContent());
        }
        if (!CollectionUtils.isEmpty(param.getOverTimeList())) {
            lambda.ge(MSamplingPlan::getOverTime, param.getOverTimeList().get(0));
            lambda.le(MSamplingPlan::getOverTime, param.getOverTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getMassifId())) {
            lambda.eq(MSamplingPlan::getMassifId, param.getMassifId());
        }
        if (!StringUtils.isEmpty(param.getGmtCreateUser())) {
            lambda.eq(MSamplingPlan::getGmtCreateUser, param.getGmtCreateUser());
        }
        if (!CollectionUtils.isEmpty(param.getGmtCreateList())) {
            lambda.ge(MSamplingPlan::getGmtCreate, param.getGmtCreateList().get(0));
            lambda.le(MSamplingPlan::getGmtCreate, param.getGmtCreateList().get(1));
        }
        if (!StringUtils.isEmpty(param.getGmtModifiedUser())) {
            lambda.eq(MSamplingPlan::getGmtModifiedUser, param.getGmtModifiedUser());
        }
        if (!CollectionUtils.isEmpty(param.getGmtModifiedList())) {
            lambda.ge(MSamplingPlan::getGmtModified, param.getGmtModifiedList().get(0));
            lambda.le(MSamplingPlan::getGmtModified, param.getGmtModifiedList().get(1));
        }
        if (!StringUtils.isEmpty(param.getDelFlag())) {
            lambda.eq(MSamplingPlan::getDelFlag, param.getDelFlag());
        }
        if (!StringUtils.isEmpty(param.getType())) {
            lambda.eq(MSamplingPlan::getType, param.getType());
        }
        lambda.orderBy(true, false, MSamplingPlan::getId);
    }


    /**
     * 请求model
     */
    @Data
    @AllArgsConstructor
    private static class MSamplingPlanReqVo extends MSamplingPlan {
        private List<String> overTimeList; // 完成时间起止
        private List<String> gmtCreateList; // 创建时间起止
        private List<String> gmtModifiedList; // 更新时间起止
    }


}
